<?php
/**
 * Save Kpi's Switch
 * 
 */

use Orx\Kpi\Messages;
use Orx\Kpi\User\Preference;
$xview = Xview::instance();
$id = $xview->val('kpiid');
$followed = $xview->val('followed',false);
$dashboard = $xview->val('dashboard',false);
if(!empty($id)) {
	
	$idusr = User::current()->getId();
	try {
		try {
			$kpiPref = Fox\Dao::load(Orx\Kpi\User\Preference::className(),$idusr.':'.$id);
		} catch(Fox\Object\Exception\NotExist $e) {
			$kpi = Fox\Dao::load(Orx\Kpi::className(),$id);// Try If the KPI exists
			$kpiPref = new Preference();
			$kpiPref->setFields(array(
				'idusr' => $idusr,
				'kpiid' => $id,
				'followed' => true,
				'dashboard' => true,
			));
			
		}
	
		if($kpiPref->exists()) {
			if($followed) {
				if($kpiPref->followed) {
					$kpiPref->followed = false;
				} else {
					$kpiPref->followed = true;
				}
			}
			if($dashboard) {
				if($kpiPref->dashboard) {
					$kpiPref->dashboard = false;
				} else {
					$kpiPref->dashboard = true;
				}
			}
			$kpiPref->update();
		} else {
			$kpiPref->create();
		}
		Fox\Message::Success(Msg(Messages::BUNDLE,Messages::PREFERENCES_UPDATED));
	} catch(\Fox\Object\Exception\Save $e) {
		Fox\Message::Error($e);
	}
}
echo $xview->messages(true,true);